<template>
  <div style="width: 100%; height: 30px"></div>
  <div class="member">
    <div class="wrapper-title">
      <span class="title">{{$t('事件')}}（{{ total }}{{$t('个')}}）</span>
      <div class="icon-wrapper">
        <div class="icon-item" @click="deleteAll">
          <span class="iconfont icon-shanchu" ></span>
        </div>
      </div>
    </div>
    <div class="filters">
      <el-select
              v-model="eventName"
              :placeholder="$t('请选择事件类型')"
              size="large"
              style="width: 413px"
              clearable
              @change="handleEventTypeChange"
      >
        <el-option
                v-for="item in eventTypes"
                :key="item.id"
                :label="item.eventName"
                :value="item.id"
        />
      </el-select>

      <el-select
              v-model="eventLevel"
              :placeholder="$t('AI严重程度判断')"
              size="large"
              style="width: 413px; margin-left: 30px"
              clearable
              @change="handleEventLevelChange"
      >
        <el-option
                v-for="item in eventLevels"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
        />
      </el-select>
    </div>
    <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column :label="$t('头像')" width="120">
        <template #default="scope">
          <div
                  class="avatar"
                  :class="
              scope.row.eventLevel == 1
                ? 'normal'
                : scope.row.eventLevel == 2
                ? 'warning'
                : 'danger'
            "
          ></div>
        </template>
      </el-table-column>
      <el-table-column property="id" :label="$t('ID')" />
      <el-table-column property="eventName" :label="$t('事件名称')" />
      <el-table-column property="eventLevel" :label="$t('严重程度')">
        <template #default="scope">
          {{ getLevelName(scope.row.eventLevel) }}
        </template>
      </el-table-column>
      <el-table-column property="sort" :label="$t('排序')" />
      <el-table-column :label="$t('操作')" width="120">
        <template #default="scope">
          <div class="actions">
            <span class="iconfont icon-shanchu" @click="deleteItem(scope.row.id)"></span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination" v-if="total > 0">
      <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[100, 200, 300, 400]"
              :size="size"
              :disabled="disabled"
              :background="background"
              layout="prev, pager, next"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
      />
      <span class="total">{{$t('共')}}{{ total }}{{$t('条')}}</span>
    </div>
    <!-- 违规记录 -->
    <ViolationRecord
            v-if="violationRecordDialog"
            @closeViolationRecord="closeViolationRecord"
    ></ViolationRecord>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { getEventTypePage, deleteEvent, getEventType } from '@/api/index';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import ViolationRecord from './components/violationRecord.vue';
export default {
  name: 'Member',
  props: {},
  components: {
    ViolationRecord,
  },
  computed: {
    ...mapGetters({
      dicts: 'dictionary/allDictionaries', // 映射 allDictionaries 到 dicts
    }),
    eventLevels() {
      let item = this.dicts.filter(item => item.dictType == "wn_event_level")[0]
      if (item) {
        return item.dataList;
      } else {
        return []
      }
    },
    modelTypes() {
      return (
        this.dicts.find((dict) => dict.dictType === 'wn_event_level')
          ?.dataList || []
      );
    },
  },
  mounted() {
    this.getEventType();
    this.fetchData(); // 加载事件数据
  },
  data() {
    return {
      id: null,
      violationRecordDialog: false,
      Search,
      eventName: '',
      eventLevel: '',
      total: null,
      currentPage: 1,
      pageSize: 20,
      size: 'default',
      disabled: false,
      background: true,
      tableData: [],
      eventTypes: [],
      selectedItems: []
    };
  },
  methods: {
    handleSelectionChange(selectedItems){
      this.selectedItems = selectedItems;
    },
    deleteAll() {
      const selectedIds = this.selectedItems.map(
          (item) => item.id,
      );

      if (selectedIds.length === 0) {
        ElMessage({
          type: 'warning',
          message: this.$t('请选择要删除的事件！'),
        });
        return;
      }

      ElMessageBox.confirm(
          this.$t(`已选择`)  + ' ' + selectedIds.length + ' ' + this.$t(`条事件数据，删除事件信息后不能恢复，确定要删除吗？`),
          this.$t('删除确认'),
          {
            confirmButtonText: this.$t('删除'),
            cancelButtonText: this.$t('取消'),
            type: 'warning',
          },
      )
          .then(async () => {
            try {
              const { data } = await deleteEvent(selectedIds); // 使用数组传递多个 ID
              if (data.code === 0) {
                ElMessage({
                  type: 'success',
                  message: this.$t('删除成功'),
                });
                this.fetchData(); // 删除后刷新数据
              } else {
                ElMessage({
                  type: 'error',
                  message: data.message || this.$t('删除失败，请重新操作'),
                });
              }
            } catch (error) {
              console.log(error);
              ElMessage({
                type: 'error',
                message: this.$t('删除请求失败，请稍后再试'),
              });
            }
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: this.$t('取消删除'),
            });
          });
    },

    deleteItem(id) {
      ElMessageBox.confirm(
          this.$t('删除该事件信息后不能恢复，确定要删除吗？'),
          this.$t('删除确认'),
          {
            confirmButtonText: this.$t('删除'),
            cancelButtonText: this.$t('取消'),
            type: 'warning',
          },
      )
          .then(async () => {
            try {
              const { data } = await deleteEvent([id]); // 删除单个事件
              if (data.code === 0) {
                ElMessage({
                  type: 'success',
                  message: this.$t('删除成功'),
                });
                this.fetchData(); // 刷新数据
              } else {
                ElMessage({
                  type: 'error',
                  message: data.message || this.$t('删除失败，请重新操作'),
                });
              }
            } catch (error) {
              console.error('删除失败', error);
              ElMessage({
                type: 'error',
                message: this.$t('删除请求失败，请稍后再试'),
              });
            }
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: this.$t('取消删除'),
            });
          });
    },
    getLevelName(value) {
      if (this.eventLevels) {
        let target = this.eventLevels.filter(item => item.dictValue == value)[0]
        if (target) {
          return target.dictLabel
        } else {
          return value
        }
      } else {
        return value
      }
    },
    async getEventType() {
      try {
        const { data } = await getEventType();
        if (data.code === 0) {
          this.eventTypes = data.data;
        }
      } catch (error) {
        console.error('事件类型获取失败', error);
      }
    },
    // 当事件类型变化时，重新加载数据
    handleEventTypeChange(newValue) {
      this.eventName = this.eventTypes?.find(item => item.id == newValue)?.eventName;
      this.fetchData();
    },
    handleEventLevelChange(newValue) {
      this.eventLevel = newValue;
      this.fetchData();
    },
    async fetchData() {
      const params = {
        page: this.currentPage,
        count: this.pageSize,
        eventName: this.eventName,
        eventLevel: this.eventLevel,
      };
      try {
        const { data } = await getEventTypePage(params); // 请求事件数据
        if (data.code === 0) {
          this.tableData = data.data.records;
          this.total = +data.data.total;
          this.pageSize = +data.data.size;
        }
      } catch (error) {
        console.error('事件数据获取失败', error);
      }
    },
    openViolationRecord() {
      this.violationRecordDialog = true;
    },
    closeViolationRecord() {
      this.violationRecordDialog = false;
    },
    closeAddMember() {
      this.addMemberDialog = false;
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchData(); // 每页条数变化时重新请求数据
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchData(); // 翻页时重新请求数据
    },
  },
};
</script>

<style lang="scss" scoped>
.member {
  .wrapper-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .title {
      font-weight: 500;
      font-size: 24px;
      color: #ffffff;
      line-height: 38px;
    }

    .icon-wrapper {
      display: inline-flex;

      .icon-item {
        width: 30px;
        height: 30px;
        background: rgba(31, 210, 103, 0.16);
        border-radius: 50%;
        text-align: center;
        line-height: 30px;
        margin-right: 17px;
        cursor: pointer;
        transition: 0.3s ease;

        .iconfont {
          color: #fff;
        }

        &:hover {
          background: $color;
        }
      }
    }

    .sub {
      font-weight: 400;
      font-size: 14px;
      color: #eaeaea;
      margin-left: 24px;
    }

    .more {
      float: right;
      font-weight: 400;
      font-size: 16px;
      color: #dfdfdf;
      display: flex;
      align-items: center;

      i {
        font-size: 10px;
        margin-left: 10px;
      }
    }
  }

  .filters {
    margin-bottom: 30px;
  }

  .avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;

    &.danger {
      border: 4px solid #ff7171;
    }

    &.warning {
      border: 4px solid #ffcc00;
    }

    &.normal {
      border: 4px solid #1fd267;
    }
  }

  .actions {
    .iconfont {
      font-size: 20px;
      transition: 0.3s ease;
      margin-right: 26px;
      cursor: pointer;

      &:hover {
        color: $color;
      }
    }
  }
}
</style>
